<!DOCTYPE html><html lang="[&quot;zh-Hans&quot;,&quot;zh-CN&quot;,&quot;default&quot;]"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="js判断浏览器窗口的关闭与刷新"><meta name="keywords" content="JavaScript"><meta name="author" content="wenmu"><meta name="copyright" content="wenmu"><title>js判断浏览器窗口的关闭与刷新 | 温木的博客</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.6.1"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.6.1"><link rel="dns-prefetch" href="https://cdn.staticfile.org"><link rel="dns-prefetch" href="https://cdn.bootcss.com"><link rel="dns-prefetch" href="https://creativecommons.org"><link rel="dns-prefetch" href="http://ta.qq.com"><script>(function() {
   var hm = document.createElement("script");
   hm.src = "https://tajs.qq.com/stats?sId=&lt;script type=&quot;text/javascript&quot; src=&quot;http://tajs.qq.com/stats?sId=66523541&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;";
   var s = document.getElementsByTagName("script")[0];
   s.parentNode.insertBefore(hm, s);
 })();</script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  }
} </script><meta name="generator" content="Hexo 4.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#最终解决方法"><span class="toc-number">1.</span> <span class="toc-text">最终解决方法</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://i.loli.net/2020/02/27/xwaBoOj158MfNyq.jpg"></div><div class="author-info__name text-center">wenmu</div><div class="author-info__description text-center">记录一些在工作中或学习新知识时学到的一些知识点；正所谓好记性不如一个烂笔头，温故而知新！</div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">115</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">52</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">30</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">温木的博客</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus"><a class="site-page" href="/">首页</a><a class="site-page" href="/archives">文章</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a></span></div><div id="post-info"><div id="post-title">js判断浏览器窗口的关闭与刷新</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-06-19</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/JavaScript/">JavaScript</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>今日项目遇到一个问题，有一个功能会在浏览器的主窗口中新开一个窗口，然后业务要求：关闭新窗口的时候往后端发个请求，刷新的时候不发送。知道有个 onbeforeunload 事件是用于捕获关闭浏览器事件（包括刷新）的，但刷新也会走此方法，所以行不通，于是就网上找了找资料，网上回答的最多的大致是这样的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onbeforeunload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">//鼠标相对于用户屏幕的水平位置 - 窗口左上角相对于屏幕左上角的水平位置 = 鼠标在当前窗口上的水平位置</span></span><br><span class="line">  <span class="keyword">var</span> n = <span class="built_in">window</span>.event.screenX - <span class="built_in">window</span>.screenLeft;</span><br><span class="line">  <span class="comment">//鼠标在当前窗口内时，n&lt;m，b为false；鼠标在当前窗口外时，n&gt;m，b为true。20这个值是指关闭按钮的宽度</span></span><br><span class="line">  <span class="keyword">var</span> b = n &gt; <span class="built_in">document</span>.documentElement.scrollWidth - <span class="number">20</span>;</span><br><span class="line">  <span class="comment">//鼠标在客户区内时，window.event.clientY&gt;0；鼠标在客户区外时，window.event.clientY&lt;0</span></span><br><span class="line">  <span class="keyword">if</span> ((b &amp;&amp; <span class="built_in">window</span>.event.clientY &lt; <span class="number">0</span>) || <span class="built_in">window</span>.event.altKey || <span class="built_in">window</span>.event.ctrlKey) &#123;</span><br><span class="line">    <span class="comment">//关闭浏览器时你想做的事</span></span><br><span class="line">    alert(<span class="string">"关闭"</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (event.clientY &gt; <span class="built_in">document</span>.body.clientHeight || event.altKey) &#123;</span><br><span class="line">    <span class="comment">//刷新浏览器时你想做的事</span></span><br><span class="line">    alert(<span class="string">"刷新"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>但是，这个方法是监听浏览器右上角的关闭事件的，我想要的是选项卡的关闭与刷新事件，下面我们先来分析一下关闭窗口相关的几个方法</p>
<blockquote>
<p>页面关闭时先执行 onbeforeunload，然后 onunload<br>页面刷新时先执行 onbeforeunload，然后 onunload，最后 onload。</p>
</blockquote>
<p>从上面的分析中，发现关闭与刷新都会走 onbeforeunload 与 onunload，如果我们认为用这两个方法无法区分关闭与刷新事件，那就大错特错了，正因为关闭与刷新事件都会走 onbeforeunload 与 onunload，所以我们利用了一个关键点就能区分出这两种，那就是：<code>时间差</code></p>
<h2 id="最终解决方法"><a href="#最终解决方法" class="headerlink" title="最终解决方法"></a>最终解决方法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">var beginTime &#x3D; 0；&#x2F;&#x2F;执行onbeforeunload的开始时间</span><br><span class="line">var differTime &#x3D; 0;&#x2F;&#x2F;时间差</span><br><span class="line">window.onunload &#x3D; function ()&#123;</span><br><span class="line">        differTime &#x3D; new Date().getTime() - beginTime;</span><br><span class="line">        if(differTime &lt;&#x3D; 5) &#123;</span><br><span class="line">            console.log(&quot;浏览器关闭&quot;)</span><br><span class="line">             $.ajax(&#123;</span><br><span class="line">                type: &quot;POST&quot;,</span><br><span class="line">                url:url,</span><br><span class="line">                dataType: &quot;JSON&quot;,</span><br><span class="line">                cache: false,</span><br><span class="line">                success: function(msg)&#123;</span><br><span class="line">                    console.log(msg);</span><br><span class="line">                    &#125;,</span><br><span class="line">                error:function(err)&#123;</span><br><span class="line">                    console.log(err)</span><br><span class="line">                &#125;</span><br><span class="line">             &#125;)</span><br><span class="line">        &#125;else&#123;</span><br><span class="line">            console.log(&quot;浏览器刷新&quot;)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    window.onbeforeunload &#x3D; function ()&#123;</span><br><span class="line">       beginTime &#x3D; new Date().getTime();</span><br><span class="line">    &#125;;</span><br></pre></td></tr></table></figure>

<p>分析：虽然刷新与关闭都会走 onbeforeunload 与 onunload，但可能因为刷新在加载新页面前内部机制还需要做一些准备工作，所以刷新事件在执行到 onunload 事件时，用的时间会比关闭事件时间长，在我的测试页面中，页面里面没啥内容，关闭时 onbeforeunload 与 onunload 的时间差一般会在 3 毫秒内，而刷新事件的时间差一般会在 10 毫秒以上，当我真正用到项目中的时候（真正的项目页面中就有很多内容了），刷新事件的时间差竟能达到 100 毫秒左右，而关闭事件时间差还是 3 毫秒左右，这就大大保证了此方法的准确率，所以，判断浏览器窗口或者说是选项卡的关闭与刷新，此方法是比较合适的。<br>————————————————<br>版权声明：本文为 CSDN 博主「微行」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。<br>原文链接：<a href="https://blog.csdn.net/itlsq/article/details/81095323" target="_blank" rel="noopener">https://blog.csdn.net/itlsq/article/details/81095323</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">wenmu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.wangpengpeng.site/2020/06/19/js%E5%88%A4%E6%96%AD%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AA%97%E5%8F%A3%E7%9A%84%E5%85%B3%E9%97%AD%E4%B8%8E%E5%88%B7%E6%96%B0/">http://blog.wangpengpeng.site/2020/06/19/js%E5%88%A4%E6%96%AD%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AA%97%E5%8F%A3%E7%9A%84%E5%85%B3%E9%97%AD%E4%B8%8E%E5%88%B7%E6%96%B0/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.wangpengpeng.site">温木的博客</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaScript/">JavaScript</a></div><div class="post-qr-code"><div class="post-qr-code-item"><img class="post-qr-code__img" src="https://i.loli.net/2020/02/27/hOBzIxFDJMCrmtN.jpg"><div class="post-qr-code__desc">微信打赏</div></div></div><nav id="pagination"><div class="next-post pull-right"><a href="/2020/06/19/%E5%8A%A8%E6%80%81%E6%9B%B4%E6%94%B9keyframes/"><span>动态更改keyframes</span><i class="fa fa-chevron-right"></i></a></div></nav><div id="vcomment"></div><script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script>var notify = 'false' == true ? true : false;
var verify = 'false' == true ? true : false;
var GUEST_INFO = ['nick','mail','link'];
var guest_info = 'nick,mail,link'.split(',').filter(function(item){
  return GUEST_INFO.indexOf(item) > -1
});
guest_info = guest_info.length == 0 ? GUEST_INFO :guest_info;
window.valine = new Valine({
  el:'#vcomment',
  notify:notify,
  verify:verify,
  appId:'U1QqpeQNuBnRsfygHk1GQ30q-gzGzoHsz',
  appKey:'dunDQzEseDzgsKgw4qLQcog1',
  placeholder:'支持markdown！',
  avatar:'wavatar',
  guest_info:guest_info,
  pageSize:'20',
  lang: 'zh-cn'
})</script></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2019 - 2020 By wenmu</div><div class="framework-info"><span>驱动 - </span><a href="http://hexo.io" target="_blank" rel="noopener"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a href="https://github.com/Molunerfinn/hexo-theme-melody" target="_blank" rel="noopener"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv">该文访问量<span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.6.1"></script><script src="/js/fancybox.js?version=1.6.1"></script><script src="/js/sidebar.js?version=1.6.1"></script><script src="/js/copy.js?version=1.6.1"></script><script src="/js/fireworks.js?version=1.6.1"></script><script src="/js/transition.js?version=1.6.1"></script><script src="/js/scroll.js?version=1.6.1"></script><script src="/js/head.js?version=1.6.1"></script><script>if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
}</script></body></html>